package com.interview.ujiuye10;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface UserService{
    int saveUser();
    int deleteUser();
}
class UserServiceImpl implements  UserService{
    public int saveUser(){
        System.out.println("执行保存方法......");
        return 100;
    }

    @Override
    public int deleteUser() {
        return 0;
    }
}

class UserServiceProxy implements UserService{

    private UserService userService;
    public UserServiceProxy(UserService userService){
        this.userService = userService;
    }

    @Override
    public int saveUser() {
        before();
        int result = userService.saveUser();
        after();
        return result-100;
    }

    @Override
    public int deleteUser() {
        return 0;
    }

    public void before(){
        System.out.println("======方法调用之前:收取小费========");
    }

    public void after(){
        System.out.println("=======方法调用之后:执行结算");

    }
}
//创建动态代理对象
class ProxyFactory  implements InvocationHandler {
    //传入被代理对象
    private Object target;
    public ProxyFactory(Object target){
        this.target = target;
    }

    //返回生成的代理对象
    public Object getInstance(){

        Object proxy = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),//类加载器
                target.getClass().getInterfaces(), //类实现的接口
                this
        );

        return proxy;
    }

    //调用真实对象的方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String name = method.getName();
        System.out.println("真实方法的名称："+name);
        before();
        //调用真实方法
        Object result = method.invoke(target,args);//args方法的参数
        after();
        return result;
    }

    public void before(){
        System.out.println("======方法调用之前:收取小费========");
    }

    public void after(){
        System.out.println("=======方法调用之后:执行结算");

    }
}





public class ProxyDemo {

    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        ProxyFactory proxyFactory = new ProxyFactory(userService);
        UserService instance = (UserService) proxyFactory.getInstance();
        System.out.println("代理类的名称:"+instance.getClass().getName());
        int i = instance.deleteUser();
        System.out.println(i);
    }

    private static void test1() {
        UserService userService = new UserServiceImpl();

        UserServiceProxy proxy = new UserServiceProxy(userService);
        int i = proxy.saveUser();
        System.out.println(i);
    }


}
